<?php
/* ******************************
 *	Product Price List aJax actions
 * ******************************
 */
 
include('../../includes/classes/core.php');
include('../../includes/classes/log.class.php');

$log 		= new log();

$action 	= $_REQUEST['act'];
$user_id	= $_COOKIE['USERID'];
$error 		= '';
$data 		= '';
	
switch ($action) {
    case 'get_add_page':
    	$page		= GetPage();
		$data		= array('page'	=> $page);
		
        break;
    case 'get_edit_page':
	    $prod_id	= $_REQUEST['id'];
		$page		= GetPage(GetProduct($prod_id));

        
        $data 		= array('page'	=> $page);
        
        break;
    case 'get_list':
	    $count = $_REQUEST['count'];
	    $hidden = $_REQUEST['hidden'];
	    
        $rResult = mysql_query("SELECT    `pricelist`.`id` AS `id`, 
        								  `production`.`code`,
								          `production`.`name`, 
								           ROUND(`reserve`.`price` , 2) AS `price`,
        								 `pricelist`.`price_wholesale` AS `pwPrice`,
								          `pricelist`.`price` AS `pPrice` 
								         
								FROM      `pricelist`
								JOIN `production` ON  `pricelist`.`production_id` = `production`.`id`
								JOIN `reserve` ON  `pricelist`.`production_id` = `reserve`.`production_id`
								WHERE     `pricelist`.`actived` = 1
								GROUP BY   reserve.production_id ");
		
		$data = array(
			"aaData"	=> array()
		);
		
		while ( $aRow = mysql_fetch_array( $rResult ) )
		{
			$row = array();
			for ( $i = 0 ; $i < $count ; $i++ )
			{
				/* General output */
				$row[] = $aRow[$i];
				if($i == ($count - 1)){
					$row[] = '<input type="checkbox" name="check_' . $aRow[$hidden] . '" class="check" value="' . $aRow[$hidden] . '" />';
				}
			}
			$data['aaData'][] = $row;
		}
		
        break;
    case 'get_price':
		$prod_name	= $_REQUEST['p_name'];
		$prod_id 	= GetProductID($prod_name);
		
		
		
		       	$self_price = number_format(GetSelfPrice($prod_id), 2, '.', '');
		       	$last_price = number_format(GetLastPrice($prod_id), 2, '.', '');
	
       	
       	$data = array('self_price' => $self_price,
       				  'last_price' => $last_price
       	);

        break;
    case 'save_prod':
		$price_id 		= $_REQUEST['id'];
		
    	$prod_name 		= $_REQUEST['n'];
		$sp_price	 	= $_REQUEST['sp'];
		$sb_price 		= $_REQUEST['sb'];
		
		if(empty($sb_price))
			$sb_price = 0;
		
		$prod_id 	= GetProductID($prod_name);
		
		if($prod_name != '' && $price_id == ''){
			if(!CheckProductExist($prod_id)){
				AddProduct($user_id, $prod_id, $sp_price, $sb_price);
				
				GLOBAL $log;
				$log->setInsertLog('pricelist');
			}else{
				$error = $prod_name . ' უკვე არის სიაში!';
			}
		}else{
			SaveProduct($user_id, $price_id, $prod_id, $sp_price, $sb_price);
		}
		
        break;
    case 'disable':
		$prod_id = $_REQUEST['id'];
		DisableProduct($prod_id);
		
        break;
    default:
       $error = 'Action is Null';
}

$data['error'] = $error;

echo json_encode($data);


/* ******************************
 *	Product Price List Functions
 * ******************************
 */

function AddProduct($user_id, $prod_id, $prod_price, $prod_sp_price){
	global  $error;
	
	if($prod_price >= $prod_sp_price){
	mysql_query("INSERT INTO `pricelist`
					(`user_id`, `production_id`, `price`, `price_wholesale`) 
				 VALUES
					($user_id, $prod_id, $prod_price, $prod_sp_price)");
	}else {
		$error='არ შეიძება საბითუმო ფასი მეტი იყოს საცალო ფასზე';
	};
}

function SaveProduct($user_id, $price_id, $prod_id, $prod_price, $prod_sp_price) 
{
	GLOBAL $log;
	$log->setUpdateLogBefore('pricelist', $price_id);
	
	mysql_query("UPDATE
	    			`pricelist`
				 SET
				 	`user_id`			= $user_id,
				 	`production_id`		= $prod_id,
				    `price`				= $prod_price,
					`price_wholesale`	= $prod_sp_price
				 WHERE
					`id` = $price_id");
	
	$log->setUpdateLogAfter('pricelist', $price_id);
}

function GetRecipieSelfPrice($prod_id)
{
	$res = mysql_fetch_assoc(mysql_query("SELECT 			ROUND(SUM((SELECT DISTINCT reserve.price FROM reserve WHERE reserve.production_id = rec.ingredient_id ) * rec.quantity * rec.default_amount),2)  AS `self_price`       
											FROM         	`recipie` AS rec 
											LEFT JOIN 		`production` ON `production`.`id` = `rec`.`recipie_id`
											WHERE 			rec.recipie_id = $prod_id AND `production`.`id` IN (SELECT `recipie_id` FROM `recipie`) AND `production`.`actived` = 1 
											GROUP BY     	rec.recipie_id
			"));
	
	return round($res['self_price'], 2);
}

function GetSelfPrice($prod_id)
{ 

	$res = mysql_fetch_assoc(mysql_query("
    									SELECT				ROUND(reserve.price , 2)  AS price		
										FROM  				reserve 
										LEFT JOIN      		production	ON	reserve.production_id = production.id
										WHERE            	production.id = '$prod_id' 
										GROUP BY     		reserve.production_id
										 "));

    
	return round($res['price'], 2);
}

function GetLastPrice($prod_id)
{
	
	$res = mysql_fetch_assoc(mysql_query("	SELECT  	`reserve`.`real_price` AS `real_price`
											FROM  		`reserve`
										   	WHERE 		`reserve`.`production_id` = $prod_id
											ORDER BY 	`reserve`.`id` DESC
											LIMIT 1"));
	
	return round($res['real_price'], 2);
}

function CheckProductExist($prod_id) 
{
    $res = mysql_fetch_assoc(mysql_query("SELECT `id`
										  FROM `pricelist`
										  WHERE `production_id` = $prod_id && `actived` = 1"));
	if($res['id'] != ''){
		return true;
	}
	return false;
}
	
function DisableProduct($prod_id)
{
    mysql_query("DELETE FROM `pricelist`
				 WHERE	`id` = $prod_id ");
}

function GetProductID($prod_name) 
{
	$prod_name = htmlspecialchars($prod_name, ENT_QUOTES);
    $res = mysql_fetch_assoc(mysql_query("SELECT	`id`
										  FROM		`production`
										  WHERE		`name` = '$prod_name'"));
	return $res['id'];
}

function GetProduct($prod_id) 
{
    $res = mysql_fetch_assoc(mysql_query("SELECT	 	`pricelist`.`id` AS `id`, 
														`production`.`name`,
														`production`.`id` AS `prod_id`,
														 ROUND(`reserve`.`price` , 2) AS t_price,
														`pricelist`.`price` AS `sp_price`, 
														`pricelist`.`price_wholesale` AS `sb_price`
											FROM  	     pricelist 
											LEFT JOIN    production ON pricelist.production_id = production.id
											LEFT JOIN    reserve ON pricelist.production_id = reserve.production_id 
		    						            WHERE    pricelist.id = $prod_id && reserve.price IS NOT NULL
											GROUP BY     reserve.production_id
    									"));
	return $res;
}

function GetPage($res = '')
{
	
	
		$last_price = GetLastPrice($res['prod_id']);
		if($last_price == 0){
			$last_price = '';
		}
		$price		= $res['sp_price'];
		if (!empty($res)) {
			$percent	= round(((100*($price - $last_price))/$last_price), 2);
		}
		

	
	$data = '
	<div id="dialog-form">
	    <fieldset>
	    	<legend>ძირითადი ინფორმაცია</legend>
	    	
	    	<table cellpadding="0" cellspacing="0" border="0" class="dialog-form-table">
				<tr>
					<td style="width: 170px;"><label for="prod_name">დასახელება</label></td>
					<td>
						<div class="seoy-row" id="prod_name_seoy">
							<input type="text" id="prod_name" class="idle seoy-address" onblur="this.className=\'idle seoy-address\'" onfocus="this.className=\'activeField seoy-address\'" value="' . $res['name'] . '" />
							<button id="prod_name_btn" class="combobox">prod_name</button>
						</div>
					</td>
				</tr>
									
				<tr>
					<td><label for="t_price">თვით ღირებულება</label></td>
					<td><input type="text" id="t_price" disabled="disabled" class="idle price" value="' . $res['t_price'] . '" onblur="this.className=\'idle price\'" onfocus="this.className=\'activeField price\'" /></td>
				</tr>
				<tr>
					<td><label for="l_price">ბოლო შეძენის ფასი</label></td>
					<td><input type="text" id="l_price" disabled="disabled" class="idle price" value="' . $last_price . '" onblur="this.className=\'idle price\'" onfocus="this.className=\'activeField price\'" /></td>
				</tr>
				<tr>
					<td><label for="percent">ფასნამატი %</label></td>
					<td><input type="text" id="percent" class="idle price" onblur="this.className=\'idle price\'" onfocus="this.className=\'activeField price\'" value="' . $percent . '" /></td>
				</tr>
				<tr>
					<td><label for="sp_price">საცალო ფასი</label></td>
					<td><input type="text" id="sp_price" class="idle price" onblur="this.className=\'idle price\'" onfocus="this.className=\'activeField price\'" value="' . $price . '" /></td>
				</tr>
				<tr>
					<td><label for="sb_price">საბითუმო ფასი</label></td>
					<td><input type="text" id="sb_price" class="idle price" onblur="this.className=\'idle price\'" onfocus="this.className=\'activeField price\'" value="' . $res['sb_price'] . '" /></td>
				</tr>
			</table>
			<!-- ID -->
			<input type="hidden" id="prod_id" value="' . $res['id'] . '" />
        </fieldset>
    </div>
    ';
	return $data;
}
?>